<template>
  <!--  手工输入-->
  <component
       :is="getComponent" :value="value" :item="item" :multipleValue="multipleValue"
       :config="config" :actionList="actionList" :disabled="disabled" :listForm="listForm"
       @updateMultipleValue="updateMultipleValue"
       @updateValue="updateValue"
       @selectedRow="selectedRow"
       @selectedsRow="selectedsRow"
       @selectedTreeRow="selectedTreeRow"
       @setOptions="setOptions"
       :treeForm="treeForm"
  ></component>
</template>

<script>

export default {
  name: "index",
  props: {
    actionList: {
      type: Array,
      default: () => []
    },
    config: {
      type: Object,
      default: () => {}
    },
    item: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    },
    allList: {
      type: Array,
      default: () => []
    },
  },

  data() {
    return {
      localItem: {...this.item},
      options: [],
      multipleValue: [],
      // placeholder
      placeholder: this.config.showPlaceholder || '请选择',
      // 显示内容
      // checkValue: [],
      treeForm: {
        defaultExpandAll: this.config.defaultExpandAll || false,//是否多选
        multiple: this.config.multiple || (this.config.viewTypeValue === '13' || false), //this.config.multiple || false,//是否多选
        extraForm: this.config.extraForm || {},
        open: false,
        // 标题
        title: this.config.title,
        // 请求路径
        path: this.config.path,
        isLazy: true//this.config.isLazy || false,//是否懒加载
      },
      listForm: {
        multiple: this.config.multiple || (this.config.viewTypeValue === '14' || false),
        extraForm: this.config.extraForm || {},
        searchColumn: this.setSearchColumn(),
        showField: this.config.showField,
        valueField: this.config.valueField,
        searchType: this.config.searchType || '',
        open: false,
        // 标题
        title: this.config.title,
        // 请求路径
        path: this.config.path || '',
        // 请求参数
        queryParams: this.config.queryParams || {},
        // 显示列字段
        columns: this.config.columns || [],
        // 选择的结果
        selected: {},
      },
    }
  },
  computed: {
    getComponent() {
      const prefix = 'config-'
      switch (this.config.viewTypeValue) {
        case '1':
          return prefix + 'input';
          break;
        case '5':
        case '9':
        case '10':
          return prefix + 'date';
          break;
        case '11':
          return prefix + 'switch';
          break;
        case '7':
        case '8':
          return prefix + 'select';
          break;
        case '3':
        case '14':
          return prefix + 'list';
          break;
        case '12':
        case '13':
          return prefix + 'tree';
          break;
        case '15':
          if (this.actionList.length > 0) {
            return prefix + 'message';
          } else {
            return prefix + 'input';
          }
          break;
        case 'dbInput':
          return prefix + 'dbInput';
          break;
        default:
          return prefix + 'input';
          break;
      }
    },
    realValue: {
      get() {
        const item = this.localItem || {}
        return item['realValue']
      },
      set(v) {
        this.localItem['realValue'] = v
      }
    },
    checkValue: {
      get() {
        const item = this.localItem || {}
        return item['value']
      },
      set(v) {
        this.localItem['value'] = v
      }
    },
    label: {
      get() {
        const item = this.localItem || {}
        return item['label']
      },
      set(v) {
        this.localItem['label'] = v
      }
    },
    value: {
      get() {
        const item = this.localItem || {}
        return item['value']
      },
      set(v) {
        this.localItem['value'] = v
      }
    }
  },
  watch: {
    'treeForm.open': {
      immediate: true,
      handler(val) {
        if (val && this.allList.length > 0) {

          // console.log( this.treeForm.extraForm)
          // console.log( item.config.extraForm)

          let data = this.allList.find(item => ((item.elementId || item.config.extraForm.elementId) === this.treeForm.extraForm.elementId));
          if (data)
            // this.$set(this.treeForm, 'extraForm', {...this.treeForm['extraForm'], ...data.config.extraForm});
            Object.assign(this.treeForm, { ...this.treeForm, ...data.config.extraForm });

          console.log(data)


        }
      }
    },
    'listForm.open': {
      immediate: true,
      handler(val) {
        if (val && this.allList.length > 0) {
          let data = this.allList.find(item => item.config.extraForm.elementId === this.listForm.extraForm.elementId);
          if (data)
            // this.$set(this.listForm, 'extraForm', {...this.listForm['extraForm'], ...data.config.extraForm});
            Object.assign(this.listForm, { ...this.listForm, ...data.config.extraForm });
        }
      }
    },
    options(data) {
      if (this.value && this.value.length > 0 && !this.label) {
        if (data) {
          this.label = data.filter(f => {
            return this.value.includes(f[this.config.valueField])
          }).map(r => r[this.config.showField]).join(',');
        }
      }
    },
    multipleValue(val) {
      if (val && val.length > 0) {
        this.value = val.join(',');
        if (this.options) {
          this.label = this.options.filter(f => {
            return val.includes(f[this.config.valueField])
          }).map(r => r[this.config.showField]).join(',');
        }
      } else {
        this.value = '';
        this.label = '';
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {

        if (this.allList) {
          let obj = {};
          let dependElementIdList = this.allList.filter(f => {
            return f.dependElementIdList
          }).map(e => {
            if (e.dependElementIdList.includes(this.item.elementId)) {
              obj[this.item.elementId] = val;
              this.$set(e.config, 'extraForm', {...e.config['extraForm'], ...obj});
              Object.assign(e.config, {...e.config, ...obj})
            }
          });
        }

        if (val) {
          if (!['3', '12', '13', '14', '15'].includes(this.config.viewTypeValue)) {
            if (this.config.viewTypeValue === '7') {
              if (this.options.length > 0)
                this.label = this.options.find(e => e[this.config.valueField] === val)[this.config.showField];
            } else if (this.config.viewTypeValue === '11') {
              this.label = this.value === 'Y' ? '是' : '否';
            } else if (this.config.viewTypeValue === '8') {
              if (this.multipleValue.length === 0) {
                this.multipleValue = this.value.split(',');
              }
            } else {
              this.label = this.value;
            }
          }
        } else {
          if (this.config.viewTypeValue === '11') {
            this.label = '';
          }
        }
      }


    },
    'config': {
      immediate: true,
      handler(val) {
        if (val) {

          // this.$set(this.config, 'defaultProps', {
          //   label: 'dictLabel',
          //   value: 'dictValue',
          // });
          // this.$set(this.treeForm, 'multiple', val.multiple || (val.viewTypeValue === '13' || false));
          // Object.keys(val).map(key => {
          //   this.treeForm[key] = val[key];
          // })
          //
          // if (!this.config.showField)
          //   this.$set(this.config, 'showField', 'name');
          // if (!this.config.valueField)
          //   this.$set(this.config, 'valueField', 'id');
          //
          // if (this.config.viewTypeValue === '3' || this.config.viewTypeValue === '14') {
          //   Object.keys(val).map(key => {
          //     this.listForm[key] = val[key];
          //   })
          // }
          // this.$set(this.treeForm, 'showFieldFun', (val) => {
          //   return this.setValueStringify(this.config.viewTypeValue === '12' ? val[0] : val);
          // });
        }
      }
    },
    // 'config.path': {
    //   immediate: true,
    //    // deep: true,
    //   handler(val) {
    //     // this.showComponent = false;
    //     // if (val) {
    //     //   this.$set(this.treeForm, 'path', val);
    //     // }
    //
    //
    //     if (val && !['3', '12', '13', '14', '15'].includes(this.config.viewTypeValue)) {
    //       let data = deepClone(this.item);
    //       // console.log(val);
    //
    //       postAction(val, this.config.extraForm || {}).then(
    //         response => {
    //           this.$set(this.config, 'defaultProps', {
    //             label: 'dictLabel',
    //             value: 'dictValue',
    //           });
    //           // this.$set(this.config, 'options', response.data);
    //           this.config['options'] = response.data;
    //           this.value = data.value || '';
    //           // this.showComponent = true;
    //           // this.$set(this.config, 'options', response.data);
    //           // this.$forceUpdate();
    //         });
    //
    //     } else {
    //       // this.showComponent = true;
    //     }
    //   }
    // },
  },
  methods: {
    setOptions(val) {
      this.options = val;
    },
    updateValue(value) {
      this.value = value;
    },
    updateMultipleValue(values) {
      this.multipleValue = values;
    },
    setSearchColumn() {
      if (this.config.searchColumn) {
        return this.config.searchColumn
      } else {
        let arr = [];
        if (this.config.showField) {
          arr.push(
            {
              prop: this.config.showField,
              label: this.config.showField
            }
          )
        }
        if (this.config.valueField) {
          arr.push(
            {
              prop: this.config.valueField,
              label: this.config.valueField
            }
          )
        }
        return arr
      }


    },

    // <--------------------------------------树形选择------------------------------------------->
    // tree选中的行
    selectedTreeRow(val) {
      if (this.treeForm.showFieldFun) {
        // this.value = this.treeForm.showFieldFun(val);
        this.$set(this.item, 'value', this.treeForm.showFieldFun(val));
        this.$set(this.item, 'label', val.map(e => e[this.treeForm.showField]).join(','));
      }
    },
    // <--------------------------------------树形选择------------------------------------------->
    // 列表选中的行
    selectedRow(val) {
      if (this.config.showFieldFun) {
        this.label = this.config.showFieldFun(val);
        this.value = this.setValueStringify(val);
      } else if (this.config.valueFieldFun) {
        this.value = this.config.valueFieldFun(val);
        this.label = this.config.valueFieldFun(val);
      } else {
        this.setFieldValue(val);
      }
      if (this.realFieldFun) {
        this.realValue = this.realFieldFun(val);
      } else {
        this.setFieldRealValue(val);
      }
      this.$emit('selectedRow', val);
    },
    setFieldValue(val) {
      if (this.config.multiple) {
        let data = val.map(e => e[this.listForm.valueField]);
        let dataShow = val.map(e => e[this.listForm.showField]);
        this.value = data.join(',');
        this.$set(this.item, 'label', dataShow.join(','));

      } else {
        // 回显的字段内容
        this.value = val[this.listForm.valueField];
        this.$set(this.item, 'label', val[this.listForm.showField]);
      }
    }
    ,
    setFieldRealValue(val) {
      if (this.config.multiple && this.realField) {
        let dataRealField = val.map(e => e[this.realField]);
        this.realValue = dataRealField.join(',');
      } else {
        this.realValue = val[this.realField];
      }
    }
    ,
    //多选
    selectedsRow(val) {
      this.value = this.setValueStringify(val);
      this.$set(this.item, 'label', val.map(e => e[this.treeForm.showField]).join(','));
    }
    ,
    setValueStringify(val) {
      if (this.config.operationType === 'action') {// 结果   动作
        if (this.config.valueField) {
          let saveData = this.config.showField ? this.config.valueField + "," + this.config.showField : this.config.valueField;
          let fields = saveData.split(',');
          if (Array.isArray(val)) {
            let filteredArray = val.map(obj => {
              let newObj = {};
              fields.forEach(field => {
                if (obj.hasOwnProperty(field)) {
                  newObj[field] = obj[field];
                }
              });
              return newObj;
            }).filter(obj => Object.keys(obj).length !== 0);
            return JSON.stringify(filteredArray);
          } else {
            let newObj = {};
            fields.forEach(field => {
              if (val.hasOwnProperty(field)) {
                newObj[field] = val[field];
              }
            });
            return JSON.stringify(newObj);
          }
        } else {
          return JSON.stringify(val);
        }
      } else {
        if (this.config.valueField && this.config.valueField.indexOf(',') != -1) {
          return 'code======1'
        }
        if (Array.isArray(val)) {
          return val.map(e => e[this.config.valueField]).join(',');
        } else {
          return val[this.config.valueField];
        }
      }

    }


  }

}
</script>
<style lang="scss" scoped>
::v-deep .vue-treeselect__control {
  height: 32px;
  line-height: 28px;
  font-weight: 400;

  .vue-treeselect__multi-value-item {
    padding: 0;
    border: 0;
  }

  .vue-treeselect__placeholder,
  .vue-treeselect__single-value {
    font-size: 13px;
    line-height: 32px;
    color: #606266;

    label {
      font-weight: 400;
    }
  }
}

::v-deep .vue-treeselect__multi-value-label {
  padding-right: 5px;
  white-space: normal;
  //text-wrap: wrap;
  user-select: none;
}


</style>

<style scoped>
.list-ui-content {
  display: flex;
  align-items: center;

}
</style>
